import MySQLdb
import sys

db = MySQLdb.connect(user="root",passwd="",db="kdd")
c = db.cursor()
cc = db.cursor()

follower_graph = {}
item_positive_raters = {}

f = open(sys.argv[1])

for l in f:
    l = l.strip()
    p = l.split()
    user_id = p[0]
    item_id = p[1]

    if user_id not in follower_graph:
        follower_graph[user_id] = {}
        c.execute("select * from follower_graph where user_id = %s",(user_id))
        for r in c:
            follower_id = r[1]
            if follower_id not in follower_graph[user_id]:
                follower_graph[user_id][follower_id] = 1

        c.execute("select * from user_action where user_id = %s and at_count + retweet_count + comment_count > 0 and user_id != dest_user_id",(user_id))
        
        for r in c:
            follower_id = r[1]
            if follower_id not in follower_graph[user_id]:
                follower_graph[user_id][follower_id] = 1

    if item_id not in item_positive_raters:
        item_positive_raters[item_id] = {}
        c.execute("select id from user_rating where item_id = %s and user_option = 1", (item_id))
        for r in c:
            follower_id = r[0]
            if follower_id not in item_positive_raters[item_id]:
                item_positive_raters[item_id][follower_id] = 1


    rating = int(p[2])

    flag = False

    for rater in item_positive_raters[item_id]:
        if rater in follower_graph[user_id]:
            flag = True
            break
        
    if flag:
        print " ".join([user_id, item_id, str(rating) ,"1"])
    else:
        print l

f.close()
db.close()


